package com.dotandmedia.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.dotmedia.dboperations.RoleDatabaseOperations;
import com.dotmedia.entities.Role;
import com.opensymphony.xwork2.ActionSupport;

/**
 * This class is the action for listing the roles.
 * 
 * @author siddharthsaha
 * 
 */
public class RoleListAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {

	private static String LOGGED_ON = "logged.on";
	private static String ADMIN_LOGGED_ON = "admin.logged.on";
	private static String NOT_LOGGED_ON = "not.logged.on";

	private static Logger logger = Logger.getLogger("RoleListAction");

	protected Map session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	@Override
	public void setServletResponse(HttpServletResponse resp) {
		this.response = resp;
	}

	@Override
	public void setServletRequest(HttpServletRequest req) {
		this.request = req;
	}

	@Override
	public void setSession(Map session) {
		this.session = session;
	}

	/**
	 * This is the method for the action class
	 * 
	 * @return
	 */
	public String getAllRoles() {
		logger.info("IN RoleListAction");
		if (session.containsKey(LOGGED_ON)) {
			if (session.get(LOGGED_ON).equals(ADMIN_LOGGED_ON)) {
				logger.info("Getting all Roles from the database");
				List<String> allRolesExtIds = new ArrayList<String>();
				RoleDatabaseOperations roleDatabaseOperations = new RoleDatabaseOperations();
				List<Role> allRolesList = roleDatabaseOperations.getAllRoleEntities();
				for (int allRolesListIndex = 0; allRolesListIndex < allRolesList.size(); allRolesListIndex++) {
					Role currentRole = allRolesList.get(allRolesListIndex);
					allRolesExtIds.add(currentRole.getRoleExtId());
				}
				request.setAttribute("allRoles", allRolesExtIds);
				logger.info("OUT RoleListAction");
				return SUCCESS;
			} else {
				logger.info("OUT RoleListAction");
				return NOT_LOGGED_ON;
			}
		} else {
			logger.info("OUT RoleListAction");
			return NOT_LOGGED_ON;
		}
	}

}
